import axios from '../http'
import {changeCartGoodsNum} from '../../common/bus'
const api = '/api/carts/';

const error = (e) => {
  return () => console.error(e);
};



export function saveAll(list, cb, fcb = error('saveAll')) {
  axios.all(list.map(params=>axios.post(api, params)))
    .then(axios.spread(function (d) {
      changeCartGoodsNum0();
      // 多个请求现在都执行完成
      cb(d);
    })).catch(d => fcb(d));
}

export function save(params, cb, fcb = error('save')) {
  axios.post(api, params).then(d=> {
    changeCartGoodsNum0();
    cb(d);
  }).catch(d => fcb(d));
}

export function deleteCartAll(list, cb, fcb = error('deleteCartAll')) {
  axios.all(list.map(params=>axios.delete(api,{params})))
    .then(axios.spread(function (d) {
      // 多个请求现在都执行完成
      changeCartGoodsNum0();
      cb(d)
    })).catch(d => fcb(d));
}

export function listCurrentUserCart( cb, fcb = error('listCurrentUserCart')) {
  axios.get(api).then(d => {
    d.data.forEach(cart=>{
      cart.checked=false;
      cart.checkedArray=[];
    })
    cb(d.data)
  }).catch(d => fcb(d))
}


export function initCartGoodsNum() {
  changeCartGoodsNum0();
}

function countGoodsNum(cb, fcb = error('countGoodsNum')) {
  axios.get(api+'/count-goods-num').then(d => {
    cb(d.data)
  }).catch(d => fcb(d))
}

function changeCartGoodsNum0() {
  countGoodsNum(goodsNum=>{
    changeCartGoodsNum(goodsNum);
  })
}


